package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.mapper.MenuMapper;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.Menu;
import com.xxxx.server.service.IMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wyd
 * @since 2023-06-13
 */
@Service
@Slf4j(topic = "MenuServiceImpl")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {


    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 通过用户ID查询菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenuByAdminId() {


        Integer adminId = ((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();

        log.info("从SecurityContextHolder得到的用户ID为:{}",adminId);

        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();

        //从Redis中获取菜单列表
        List<Menu> menuList = (List<Menu>) valueOperations.get("menu_" + adminId);

        //如果redis中没有，则查询数据库获取
        if (CollectionUtils.isEmpty(menuList)){

            menuList = menuMapper.getMenuByAdminId(adminId);

            //存到Redis中
            valueOperations.set("menu_"+adminId,menuList);
        }

        return menuList;
    }

    @Override
    public List<Menu> getMenuByRole() {

        return menuMapper.getMenuByRole();
    }

    /**
     * 查询所有菜单
     * @return
     */
    @Override
    public List<Menu> getAllMenus() {


        return menuMapper.getAllMenus();
    }
}
